<!--
 * @Author: [kangjie]
 * @Date: 2022-04-20 14:58:13
 * @LastEditors: [kangjie]
 * @LastEditTime: 2022-04-21 13:07:19
 * @Description:
-->
<template>
  <div>
    <!-- 头部导航栏 -->
    <div class="header">
      <el-form :inline="true" :model="params" class="demo-form-inline">
        <el-button type="primary" @click="toAdd">添加</el-button>
        <el-form-item>
          <el-input
            v-model="params.name"
            placeholder="请输入产品名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="params.status" clearable placeholder="请选择状态">
            <el-option label="正常" value="正常" />
            <el-option label="下架" value="下架" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="params.productCategoryId"
            placeholder="请选择所属栏目"
            clearable
          >
            <el-option
              v-for="item in columns"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
        </el-form-item>
      </el-form>
      <!-- {{ params }} -->
    </div>
    <!-- 头部导航栏结束 -->

    <!-- 导航栏结束 -->
    <!-- 第二行 表格书写 -->
    <el-table v-loading="loading" :data="productData" style="width: 100%">
      <el-table-column type="index" :index="1" label="序号" />
      <el-table-column prop="id" label="产品编号" width="180" />
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="photo" label="图片">
        <template slot-scope="scope">
          <el-popover placement="right" trigger="hover">
            <img
              slot="reference"
              :src="scope.row.photo"
              width="30px"
              alt="加载失败"
            >
            <img width="200px" :src="scope.row.photo" alt="">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格" />
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.status === '正常'"
            type="success"
          >正常</el-tag>
          <el-tag v-else type="danger">下架</el-tag>
        </template>
      </el-table-column>
      <el-table-column le-column prop="category.name" label="所属栏目" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" plain @click="toEdit(scope.row)">编辑</el-button>
          <el-button
            v-if="scope.row.status === '正常'"
            type="danger"
            plain
            @click.prevent="changeStatus(scope.row.id, '下架')"
          >下架</el-button>
          <el-button
            v-else
            type="success"
            plain
            @click.prevent="changeStatus(scope.row.id, '上架')"
          >上架</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格结束 -->
    <!-- 第三行 分页按钮 -->
    <div class="page">
      <el-pagination
        :current-page="params.page"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 第三行结束 -->
    <!-- 添加和编辑模态框 -->
    <el-dialog :title="title" :visible.sync="visible" @close="toClose">
      <el-form ref="myForm" :rules="rules" :model="form">
        <el-form-item
          label="产品名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="所属栏目"
          :label-width="formLabelWidth"
          prop="productCategoryId"
        >
          <el-select
            v-model="form.productCategoryId"
            clearable
            placeholder="请选择所属栏目"
          >
            <el-option
              v-for="item in columns"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
          <el-input v-model="form.price" autocomplete="off" />
        </el-form-item>
        <!-- 封面 -->
        <el-form-item label="封面" :label-width="formLabelWidth" prop="photo">
          <el-upload
            class="avatar-uploader"
            :action="uploadFileURL"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="form.photo" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="产品描述" :label-width="formLabelWidth">
          <el-input v-model="form.description" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="toClose">取 消</el-button>
        <el-button type="primary" @click="toSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 模态框结束 -->
  </div>
</template>

<script>
import { uploadFileURL } from '@/utils/config'
import {
  queryColumn,
  queryProduct,
  onLine,
  offLine,
  saveOrUpdate
} from '@/api/product'
export default {
  data() {
    return {
      // 图片上传路径
      uploadFileURL,
      // 表单对象和分页数据
      params: {
        page: 1,
        pageSize: 10
      },
      // 控制白屏加载动画
      loading: false,
      // 产品数据
      productData: [],
      columns: [],
      // 产品条数
      total: 0,
      // 模态框标题
      title: '',
      // 控制模态框显示与隐藏变量
      visible: false,
      // 表单对象
      form: {},
      formLabelWidth: '120px',
      // 头像上传图片变量
      imageUrl: '',
      rules: {
        name: [{ required: true, message: '请输出产品名称', trigger: 'blur' }],
        price: [
          {
            required: true,
            message: '请输入价格,且只能为数字',
            trigger: 'blur',
            // type: 'number'
          }
        ],
        photo: [{ required: true, message: '请上传封面', trigger: 'change' }]

      }
    }
  },
  created() {
    // 查询到所有栏目 --分发栏目动作
    this.queryColumn()
    this.getProduct()
  },
  // wtach: {
  //   // 当分页数据发生改变的时候需要重新请求数据
  //   params: {
  //     // 使用此方法原意想监听pageSize和page
  //     handler() {
  //       this.getProduct();
  //     },
  //     deep: true,
  //   },
  // },
  methods: {
    // 模态框关闭回调
    toClose() {
      setTimeout(() => {
        this.$refs.myForm.resetFields()
        this.visible = false
      }, 300)
      delete this.productCategoryId
    },
    // 保存或更新
    toSubmit() {
      this.$refs.myForm.validate(async(valid) => {
        if (valid) {
          // 发送保存或更新请求
          const res = await saveOrUpdate(this.form)
          this.$notify({
            type: 'success',
            message: res.message
          })
          this.getProduct()
          this.toClose()
        } else {
          return false
        }
      })
    },
    // 编辑按钮
    toEdit(row) {
      this.title = '修改产品信息'
      this.visible = true
      this.form = { ...row }
      this.imageUrl = this.form.photo
    },
    // 添加方法
    toAdd() {
      this.visible = true
      this.title = '添加产品信息'
      this.form = {}
      this.imageUrl = ''
      this.productCategoryId = [
        { required: true, message: '请选择栏目', trigger: 'change' }
      ]
    },
    // 图片上传成功的回调
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.form.photo = res.data
    },
    // 图片上传之前的回调
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 执行上架与下架
    changeStatus(id, status) {
      // 提示用户
      this.$confirm('确认是否改变产品状态？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          if (status === '上架') {
            const res = await onLine({ id })
            this.$message({
              type: 'success',
              message: res.message
            })
          } else {
            const res = await offLine({ id })
            this.$message({
              type: 'success',
              message: res.message
            })
          }
          this.getProduct()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 页码条数发生改变的方法
    handleSizeChange(pageSize) {
      // 发生改变时需要对页码条数重新赋值，所以
      this.params.pageSize = pageSize
      this.getProduct()
      // 发生改变后返回第一页
      this.params.page = 1
    },
    // 当前页码发生改变触发的方法 默认参数page
    handleCurrentChange(page) {
      // 发生改变时需要对页码重新赋值，所以
      this.params.page = page
      this.getProduct()
    },
    // 点击 查询
    onSearch() {
      // 点击查询时候返回第一页
      this.params.page = 1
      this.getProduct()
    },
    // 查看所有栏目
    async queryColumn() {
      const res = await queryColumn(this.params)
      this.columns = res.data.list
    },
    // 分页查询产品数据方法
    async getProduct() {
      // 数据获取前加载动画
      this.loading = true
      // 要将params做筛选和判断
      for (const key in this.params) {
        // key是属性名 this.params[key]是属性值
        // 判断属性值是  否存在，即当数据为空时将数据删除
        if (!this.params[key]) {
          delete this.params[key]
        }
      }
      const res = await queryProduct(this.params)
      this.productData = res.data.list
      this.total = res.data.total
      // 获取到数据后关闭加载动画
      this.loading = false
    }
  }
}
</script>

<style lang="scss">
$color: #e65d6e;
a {
  margin-right: 10px;
}
.toEdit,
.onLine {
  color: #30b08f;
}
.offLine {
  color: $color;
}
</style>
